let fs = require('fs')
let EventEmitter = require('events')
class WriteStream extends EventEmitter {
  constructor(path, options) {
    super()
    this.path = path
    this.flags = options.flags || 'w';
    this.mode = options.mode || 438
    this.start = options.start || 0
    this.autoClose = options.autoClose || true
    this.highWaterMark = options.highWaterMark || 16*1024
    this.encoding = options.encoding || 'utf8'
    this.pos = this.start
    this.cache = []
    this.len = 0
    this.needDrain = false
    this.writing = false // 是否正在写入
    this.open()
  }
  open() {
    fs.open(this.path, this.flags, (err, fd)=>{
      if(err) {
        this.emit('error')
        return
      }
      this.fd = fd
      this.emit('open', this.fd)
    })
  }
  write(chunk, encoding=this.encoding, callback) {
    // 第一次是真正的向文件中写入  之后都放到内存中
    // 统一转成 buffer 处理
    chunk = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) 
    this.len += chunk.length
    let flag = this.len < this.highWaterMark
    if(!flag) {
      this.needDrain = true
    }
    if(this.writing) {
      this.cache.push({
        chunk,
        encoding,
        callback
      })
    }else{
      this.writing = true
      this._write(chunk, encoding, ()=>{
        callback && callback()
        this.clearBuffer()
      })
    }
    return flag
  }
  clearBuffer() {
    let obj = this.cache.shift()
    if(obj) {
      this._write(obj.chunk, obj.encoding, ()=>{
        obj.callback && obj.callback()
        this.clearBuffer()
      })
    }else{
      if(this.needDrain) {
        this.needDrain = false
        this.writing = false 
        this.emit('drain')
      }
    }
  }
  _write(chunk, encoding, callback) {
    if(typeof this.fd !== 'number') {
      return this.once('open', ()=>this._write(chunk, encoding, callback))
    }
    fs.write(this.fd, chunk, 0, chunk.length, this.pos, (err, written)=>{
      this.pos += written
      this.len -= written
      // 写入成功后
      callback()
    })
  }
  // 会强制把内存清空  并且关闭文件
  end(chunk) {
    
  }
}

module.exports = WriteStream